package com.perceptivesoftware.licensing.client.dialogs.useradmin.plugin.user;

import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.perceptivesoftware.licensing.client.common.DirtyCallbackHandler;

/**
 * <p/>
 * Copyright 2012 Perceptive Software
 * <p/>
 * Project: Perceptive DataTransfer
 * <p/>
 * Confidential and Proprietary
 * 
 * @author Nolan Brassard
 * 
 */
public class UserSettingsTabItem extends TabItem {

	private TextField<String> email;
	private final DirtyCallbackHandler dirtyCallbackHandler;
	private boolean settingValues = false;
	private UserDTO user;

	public UserSettingsTabItem(DirtyCallbackHandler dirtyCallbackHandler) {
		super("Settings");
		this.dirtyCallbackHandler = dirtyCallbackHandler;
		buildUI();
	}

	public void setUserDto(UserDTO user) {
		settingValues = true;
		this.user = user;
		email.setValue(user.getEmail());
		settingValues = false;
	}

	private void buildUI() {
		setLayout(new FitLayout());

		final FormPanel form = new FormPanel();
		form.setLayout(new FormLayout());
		form.setFrame(true);
		form.setBorders(false);

		email = new TextField<String>();
		email.setFieldLabel("Email");
		email.addListener(Events.Change, new Listener<FieldEvent>() {

			@Override
			public void handleEvent(final FieldEvent be) {
				if (!settingValues) {
					dirtyCallbackHandler.iAmDirty();
				}
			}
		});
		form.add(email, new FormData("-10"));

		add(form);
	}

	protected UserDTO saveFieldsToDTO() {
		if (user != null) {
			if (email.getValue() != null) {
				user.setEmail(email.getValue().trim());
			}
			else {
				user.setEmail(null);
			}
		}

		return user;
	}
}